package com.base.pig.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.ui.ModelMap;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class HttpUtils {
	
	
	//封装后台模拟HTTP的POST请求，参数1形式：url  参数2形式：JSONObject
	public static String HttpUtils_RequestPost(String url, JSONObject JSONObject){
		//ModelMap mm = new ModelMap();
		String http_post_result = "";  
        BufferedReader in = null;  
        try {
        	com.alibaba.fastjson.JSONObject template = JSONObject;
            String urlString = url;
            CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(urlString);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            StringEntity entity;
            entity = new StringEntity(template.toString());
            System.out.println(template.toString());


            RequestConfig requestConfig = RequestConfig.custom()
                   .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(20000).build();
            httpPost.setConfig(requestConfig);

            httpPost.setEntity(entity);
            HttpResponse response;
            System.out.println("开始"+new Date());
            response = httpClient.execute(httpPost);
            //获取返回
          	HttpEntity entitys = response.getEntity();
          	in = new BufferedReader(new InputStreamReader(entitys.getContent(), "UTF-8"));
        	StringBuffer buffer = new StringBuffer();
          	String line = null;
          	while ((line = in.readLine()) != null) {
          	  buffer.append(line);
          	}
          	http_post_result=buffer.toString();
            System.out.println("结束"+new Date());

        } catch (Exception e) {
            http_post_result="{\"code\":\"200\",\"message\":\"timeout\",\"result\":null}";
            System.out.println("异常"+new Date());
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        } 
        //mm.put("http_post_result", http_post_result);
	    return http_post_result;
	}
    public static String HttpUtils_RequestPost(String url ){
        //ModelMap mm = new ModelMap();
        String http_post_result = "";
        BufferedReader in = null;
        try {

            String urlString = url;
            CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(urlString);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            StringEntity entity;
            HttpResponse response;
            response = httpClient.execute(httpPost);
            //获取返回
            HttpEntity entitys = response.getEntity();
            in = new BufferedReader(new InputStreamReader(entitys.getContent(), "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            http_post_result=buffer.toString();
        } catch (Exception e) {

            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        //mm.put("http_post_result", http_post_result);
        return http_post_result;
    }
	
	
	
	//封装后台模拟HTTP的GET请求，参数1形式：url  参数2形式：param1=1&param2=2&param3=3
	public static ModelMap HttpUtils_RequestGet(String url_path, String url_param){
		ModelMap mm = new ModelMap();
		String http_get_result = "";  
        BufferedReader in = null;  
        try {  
            String urlNameString = url_path + "?" + url_param;  
            URL realUrl = new URL(urlNameString);  
            System.out.println(realUrl);
            // 打开和URL之间的连接  
            URLConnection connection = realUrl.openConnection();  
            // 设置通用的请求属性  
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            connection.setRequestProperty("Charsert", "UTF-8");
            // 建立实际的连接  
            connection.connect();  
            // 获取所有响应头字段  
            Map<String, List<String>> map = connection.getHeaderFields();  
            // 遍历所有的响应头字段  
           /*for (String key : map.keySet()) {  
                System.out.println(key + "--->" + map.get(key));  
            }*/  
            // 定义 BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));  
            String line;  
            while ((line = in.readLine()) != null) {  
            	http_get_result += line;  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
        mm.put("http_get_result", http_get_result);
		return mm;
	}
		
	
	
	
	
	

}
